package com.quran.viewcontrollers;

import java.io.File;
import java.net.UnknownHostException;
import java.util.List;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.bappi.utils.AlertUtils;
import com.bappi.utils.Canceller;
import com.bappi.utils.Constants;
import com.bappi.utils.DownloadListener;
import com.bappi.utils.FileUtils;
import com.bappi.utils.MediaPlayerUtils;
import com.bappi.utils.Utils;
import com.custom.tab.AbstractTabRootManager;
import com.custom.tab.AbstractViewController;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.tos.quran.R;

public class ShowVersesController extends AbstractViewController {

	// private HashMap<String, String> hashRender;
	private ActionBar actionBar;
	private List<String[]> versesInfos;
	private VersesListAdapter versesListAdapter;
	private ListView listView;
	private View buttonContainer, bottomHelperLayout;
	private String langCode;
	private String[] suraNamesAra;
	private String[] suraNamesEng;
	private String[] suraMeaning;
	private int suraId;

	private int currentPlayingIndex;
	private Action speakAction;
	private boolean isAllPlaying;
	private boolean isPaused;
	private boolean nativeSpeakingEnabled;
//	private OnSharedPreferenceChangeListener ospcl;
	// private Bitmap playImage,pauseImage,prevImage,nextImage;
	private ImageButton playPauseButton, prevButton, nextButton;
	private boolean isNoTranslateSelected;

	private OnCompletionListener onCompletionListener = new OnCompletionListener() {

		public void onCompletion(MediaPlayer mp) {
			try {
				if ((currentPlayingIndex < (versesInfos.size() - 1))
						&& isAllPlaying) {
					currentPlayingIndex++;
					play();
				} else {
					currentPlayingIndex = -1;
					hideButtonPanel();
					versesListAdapter.notifyDataSetChanged();
				}
				// }
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	};

	private String getTitle(int index) {
		return suraNamesEng[index] + " (" + suraNamesAra[index] + ") "
				+ suraMeaning[index];
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		try {
			nativeSpeakingEnabled = sharedPreferences.getBoolean(
					 Constants.KEY_NATIVE_SPEAKING_ENABLE, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public ShowVersesController(AbstractTabRootManager tabRootManager,Bundle bundle) {
		super(tabRootManager, R.layout.show_verses);
		try {
//			ospcl = new OnSharedPreferenceChangeListener() {
//
//				public void onSharedPreferenceChanged(
//						SharedPreferences sharedPreferences, String key) {
//					 if (Constants.KEY_NATIVE_SPEAKING_ENABLE.equals(key)) {
//					 nativeSpeakingEnabled = sharedPreferences.getBoolean(
//					 Constants.KEY_NATIVE_SPEAKING_ENABLE, false);
//					 }
//				}
//			};
			playPauseButton = (ImageButton) findViewById(R.id.play_pause_button);
			prevButton = (ImageButton) findViewById(R.id.prev_button);
			nextButton = (ImageButton) findViewById(R.id.next_button);
			playPauseButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					try {
						if (isPaused) {
							MediaPlayerUtils.play();
							isPaused = false;
						} else {
							MediaPlayerUtils.pause();
							isPaused = true;
						}
						manageButtons();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			nextButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					try {
						if (currentPlayingIndex < (versesInfos.size() - 1)) {
							currentPlayingIndex++;
							play();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			prevButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					try {
						if (currentPlayingIndex > 0) {
							currentPlayingIndex--;
							play();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});

			
			
//			getActivity().getSharedPreferences().registerOnSharedPreferenceChangeListener(ospcl);
			actionBar = (ActionBar) findViewById(R.id.actionbar);
			buttonContainer = findViewById(R.id.bottom_layout);
			bottomHelperLayout = findViewById(R.id.bottom_helper_layout);
			speakAction = new Action() {
				public void performAction(View view) {
					playAllVerses();
				}

				public int getDrawable() {
					return R.drawable.ic_menu_microphone;
				}
			};
			langCode = getActivity().getSharedPreferences().getString(
					Constants.KEY_SELECTED_TRANS_CODE, Constants.LANG_CODE_NONE);
			isNoTranslateSelected = Constants.LANG_CODE_NONE.equals(langCode);

			suraNamesAra = bundle.getStringArray(
					Constants.KEY_SURA_NAMES_ARA);
			suraNamesEng = bundle.getStringArray(
					Constants.KEY_SURA_NAMES_ENG);
			suraMeaning = bundle.getStringArray(
					Constants.KEY_SURA_MEANING);
			suraId = bundle.getInt(Constants.KEY_SURA_ID, 1);
			currentPlayingIndex = -1;
			actionBar.setTitle(getTitle(suraId - 1));
			actionBar.addAction(speakAction);

			listView = (ListView) findViewById(R.id.list_view);

			loadData();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onDestroy() {
		try {
			MediaPlayerUtils.stopPlaying();
//			getActivity().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(ospcl);
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	private void loadData() {
		try {
			new AsyncTask<String, String, String>() {
				private AlertUtils.SpinnerProgressDialog spinnerProgressDialog;

				@Override
				protected void onPreExecute() {
					try {
						spinnerProgressDialog = AlertUtils.getProgressDialog(
								getActivity(),
								getString(R.string.dialog_default_title),
								getString(R.string.please_wait));
						spinnerProgressDialog.show();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				protected String doInBackground(String... arg0) {
					try {

						versesInfos = getActivity().getDatabaseAccessor()
								.getVerses(suraId, langCode);
						Log.i("DREG", "versesInfos SIZE="+versesInfos.size());

					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				protected void onPostExecute(String unused) {
					try {
						versesListAdapter = new VersesListAdapter();
						listView.setAdapter(versesListAdapter);
						spinnerProgressDialog.dismiss();
						listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

							public void onItemClick(AdapterView<?> av, View v,
									int position, long arg) {
								versesClicked(position);
							}
						});
						listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

							public boolean onItemLongClick(AdapterView<?> av,
									View v, int position, long arg) {
								versesLongClicked(position);
								return true;
							}
						});
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void versesLongClicked(final int position) {
		try {
			final Dialog dialog = new Dialog(getActivity());
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.verses_options);
			dialog.setCancelable(false);
			Button buttonAddToBookmark = (Button) dialog
					.findViewById(R.id.button_add_to_bookmark);
			Button buttonShare = (Button) dialog
					.findViewById(R.id.button_share);
			Button buttonCancel = (Button) dialog
					.findViewById(R.id.button_cancel);
			if (!Utils.isShareable(langCode)) {
				buttonShare.setVisibility(View.GONE);
			}
			buttonAddToBookmark.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					dialog.dismiss();
					addToBookmark(position);
				}
			});
			buttonShare.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {

					dialog.dismiss();
					Intent sharingIntent = new Intent(Intent.ACTION_SEND);
					// sharingIntent.setType("text/html");
					sharingIntent.setType("text/plain");
					sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,
							versesInfos.get(position)[3]);
					getActivity().startActivity(
							Intent.createChooser(sharingIntent,
									getString(R.string.sharing_intent_title)));
				}
			});
			buttonCancel.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void versesClicked(int position) {
		try {
			isAllPlaying = false;
			File file = FileUtils.getFile(getActivity(),
					Integer.toString(suraId));
			if (file.exists() && file.isDirectory()
					&& (file.listFiles().length >= versesInfos.size())) {
				currentPlayingIndex = position;
				play();
			} else {
				Utils.showAlertDialogYesNo(getActivity(),
						getString(R.string.message_download_conf),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								downloadFiles();
							}
						}, new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {

							}
						});

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void playAllVerses() {
		try {
			isAllPlaying = true;
			File file = FileUtils.getFile(getActivity(),
					Integer.toString(suraId));
			if (file.exists() && file.isDirectory()
					&& (file.listFiles().length >= versesInfos.size())) {
				currentPlayingIndex = 0;
				play();
			} else {
				Utils.showAlertDialogYesNo(getActivity(),
						getString(R.string.message_download_conf),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								downloadFiles();
							}
						}, new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {

							}
						});

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public class VersesListAdapter extends BaseAdapter {

		private LayoutInflater mInflater;

		public VersesListAdapter() {
			mInflater = (LayoutInflater) getActivity().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			return versesInfos.size();
		}

		public Object getItem(int arg0) {
			Object ret = null;
			if (versesInfos != null && versesInfos.size() > arg0) {
				ret = versesInfos.get(arg0);
			}
			return ret;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			try {
				ViewHolder holder;
				if (convertView == null) {
					convertView = mInflater.inflate(
							R.layout.verses_list_content, null);
					holder = new ViewHolder();
					holder.mainContainer = convertView
							.findViewById(R.id.main_container);
					holder.versesAra = (TextView) convertView
							.findViewById(R.id.view_verses_ara);
					holder.versesAra.setLineSpacing(Constants.SPACING_FACTOR
							* holder.versesAra.getPaint().getTextSize(), 1);
					holder.versesOthers = (TextView) convertView
							.findViewById(R.id.view_verses_others);

					if (isNoTranslateSelected) {
						holder.versesOthers.setVisibility(View.GONE);
					} else {
						holder.versesOthers.setVisibility(View.VISIBLE);
					}

					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
				// holder.versesAra.setSpecialChars(versesInfos.get(position)[2]);
				holder.versesAra.setText(versesInfos.get(position)[1]);
				if (!isNoTranslateSelected) {
					holder.versesOthers.setText(versesInfos.get(position)[3]);
				}
				if (currentPlayingIndex == position) {
					holder.mainContainer.setBackgroundColor(0x44000000);
				} else {
					holder.mainContainer.setBackgroundColor(0x00000000);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

		class ViewHolder {
			View mainContainer;
			TextView versesAra;
			TextView versesOthers;
		}
	}

	private void downloadFiles() {
		try {
			try {
				new AsyncTask<String, String, String>() {
					private int percent;
					private String exception;
					private ProgressDialog progressDialog;
					private Canceller canceller;

					protected void onPreExecute() {
						try {
							percent = 0;
							canceller = new Canceller();
							progressDialog = Utils.getProgressDialog(
									getActivity(),
									getString(R.string.downloading), null,
									getString(R.string.cancel),
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											canceller.cancel();
										}
									});
							progressDialog.show();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					protected void onProgressUpdate(String... values) {
						progressDialog.setProgress(percent);
					}

					protected String doInBackground(String... arg0) {
						try {

							FileUtils.downloadFullSura(getActivity(),
									Constants.FILE_DOWNLOAD_URL, suraId,
									versesInfos.size(), canceller,
									new DownloadListener() {
										public void progress(int p) {
											if (percent != p) {
												percent = p;
												publishProgress();
											}
										}

										public void downloadedCompleted() {
										}
									});
						} catch (UnknownHostException uhe) {
							exception = getString(R.string.message_go_online);
							uhe.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
							exception = e.getLocalizedMessage();
						}
						return null;
					}

					protected void onPostExecute(String unused) {
						try {
							progressDialog.dismiss();
							if (exception != null) {
								Utils.showAlertDialog(getActivity(), exception);
							} else if (!canceller.isCanclled()) {
								play();
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}.execute();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void play() throws Exception {
		isPaused = false;
		manageButtons();
		showButtonPanel();
		versesListAdapter.notifyDataSetChanged();
		if ((currentPlayingIndex < listView.getFirstVisiblePosition())
				|| (currentPlayingIndex >= listView.getLastVisiblePosition())) {
			listView.setSelection(currentPlayingIndex);
		}
		MediaPlayerUtils.playFile(getActivity(), FileUtils.getFile(
				getActivity(), Integer.toString(suraId), String.format(
						"%03d%03d.mp3", suraId, (currentPlayingIndex + 1))),
				onCompletionListener);
	}

	private void addToBookmark(final int position) {
		try {
			new AsyncTask<String, String, String>() {
				private ProgressDialog progressDialog;
				private boolean added;

				@Override
				protected void onPreExecute() {
					try {
						progressDialog = new ProgressDialog(getActivity());
						progressDialog
								.setProgressStyle(ProgressDialog.STYLE_SPINNER);
						progressDialog.setCancelable(true);
						progressDialog.setIndeterminate(true);
						progressDialog.show();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				protected String doInBackground(String... arg0) {
					int versesId = Integer
							.parseInt(versesInfos.get(position)[0]);
					added = getActivity().getDatabaseAccessor().addToBookmark(
							versesId, suraId, (position + 1),
							suraNamesAra[suraId - 1], suraNamesEng[suraId - 1],
							suraMeaning[suraId - 1]);
					getActivity().getSharedPreferences()
							.edit()
							.putLong(Constants.KEY_BOOKMARK_CHANGED_CODE,
									System.currentTimeMillis()).commit();
					return null;
				}

				protected void onPostExecute(String unused) {
					try {
						progressDialog.dismiss();
						if (added) {
							Utils.showAlertDialog(getActivity(),
									getString(R.string.added_to_bookmark));
						} else {
							Utils.showAlertDialog(
									getActivity(),
									getString(R.string.already_added_to_bookmark));
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void manageButtons() {
		try {
			if (currentPlayingIndex > 0) {
				prevButton.setEnabled(true);
			} else {
				prevButton.setEnabled(false);
			}
			if (currentPlayingIndex < (versesInfos.size() - 1)) {
				nextButton.setEnabled(true);
			} else {
				nextButton.setEnabled(false);
			}
			if (isPaused) {
				playPauseButton.setImageResource(R.drawable.play);
			} else {
				playPauseButton.setImageResource(R.drawable.pause);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void showButtonPanel() {
		try {
			if (buttonContainer.getVisibility() != View.VISIBLE) {

				Animation animation = new TranslateAnimation(
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 1.0f,
						Animation.RELATIVE_TO_SELF, 0.0f);
				animation.setDuration(600);
				animation
						.setAnimationListener(new Animation.AnimationListener() {

							public void onAnimationStart(Animation animation) {
								// TODO Auto-generated method stub

							}

							public void onAnimationRepeat(Animation animation) {
								// TODO Auto-generated method stub

							}

							public void onAnimationEnd(Animation animation) {
								try {
									bottomHelperLayout.getLayoutParams().height = buttonContainer
											.getHeight();
									listView.requestLayout();
								} catch (Exception e) {
									e.printStackTrace();
								}

							}
						});
				buttonContainer.startAnimation(animation);
				buttonContainer.setVisibility(View.VISIBLE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void hideButtonPanel() {
		try {
			if (buttonContainer.getVisibility() == View.VISIBLE) {
				bottomHelperLayout.getLayoutParams().height = 0;
				Animation animation = new TranslateAnimation(
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 1.0f);
				animation.setDuration(600);
				buttonContainer.startAnimation(animation);
				buttonContainer.setVisibility(View.GONE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
